package com.njust.interceptor;



import com.njust.common.TokenCache;
import com.njust.exception.QixiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



/**
 * 登入拦截（token拦截)每次请求的时候都会带token
 * @author zjwpro@foxmail.com
 * @date 2018/1/13 下午7:57
 */
//@slf4j实现日志输出,
// 如果不想每次都写private  final Logger logger = LoggerFactory.getLogger(XXX.class);
// 可以用注解@Slf4j
@Slf4j
public class LoginInterceptor implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("开启token拦截功能");
        String url = request.getRequestURL().toString();//获取请求地址,全路径
        String method = request.getMethod();//获取请求方式
        String uri = request.getRequestURI();//返回除去host(域名或者ip)部分的路径
        String queryString = request.getQueryString(); //获取查询字符串,即参数
        System.out.println(request.getParameterMap());
        //以注解的方式写入日志,@slf4j
        log.info(String.format("请求参数, url: %s, method: %s, uri: %s, params: %s", url, method, uri, queryString));
        //token在request头中获取token,即从前端获取的token
        String qianduantoken=StringUtils.substring(request.getHeader("Authorization"),7);
        String username=request.getHeader("currentUser");//获取当前用户名
        System.out.println(username);

        System.out.println(qianduantoken);
        String houtaitoken= TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);//缓存中获取的token
        log.info("gettoken_key={}",TokenCache.TOKEN_PREFIX+username);
        System.out.println(houtaitoken);

        if(request.getMethod().equals("OPTIONS")){
            return true;
        }
        if(StringUtils.isBlank(qianduantoken)){
            System.out.println("没有 token");
            throw new QixiException(-1,"请先登入");
        }
        if(StringUtils.equals(qianduantoken,houtaitoken)){
            System.out.println("token相等");
            return true;
        }
        System.out.println("token无效");
        response.setStatus(403);
        throw new QixiException(-2,"token无效");
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
